package org.arithmetic.sort;

/**
 * Created by LUOLIANG on 2016/8/26.
 * 直接插入排序
 */
public class InsertSort {

    public static void sort(int[] numbers) {
        System.out.println("排序前：");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }

        for (int i = 0; i < numbers.length; i++) {
            int temp = numbers[i];
            int j;

            for (j = i - 1; j >= 0; j--) {
                if (numbers[j] > temp) {
                    numbers[j + 1] = numbers[j];
                } else {
                    //else的作用，如果numbers[j]<temp，那么numbers[j]之前的所有数字都小于temp
                    break;
                }
            }
            numbers[j + 1] = temp;
        }

        System.out.println("\n排序后：");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }
    }

    public static void main(String[] args) {
        int n[] = {21, 234, 5, 12, 34, 56, 78};

        sort(n);
    }
}
